home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / python-support / python-gdata / atom / __init__.py next >
Encoding:
Python Source  |  2009-02-11  |  46.0 KB  |  1,407 lines

  1. #
  2. # Copyright (C) 2006 Google Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. #      http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15.  
  16.  
  17. """Contains classes representing Atom elements.
  18.  
  19.   Module objective: provide data classes for Atom constructs. These classes hide
  20.   the XML-ness of Atom and provide a set of native Python classes to interact 
  21.   with.
  22.  
  23.   Conversions to and from XML should only be necessary when the Atom classes
  24.   "touch the wire" and are sent over HTTP. For this reason this module 
  25.   provides  methods and functions to convert Atom classes to and from strings.
  26.  
  27.   For more information on the Atom data model, see RFC 4287 
  28.   (http://www.ietf.org/rfc/rfc4287.txt)
  29.  
  30.   AtomBase: A foundation class on which Atom classes are built. It 
  31.       handles the parsing of attributes and children which are common to all
  32.       Atom classes. By default, the AtomBase class translates all XML child 
  33.       nodes into ExtensionElements.
  34.  
  35.   ExtensionElement: Atom allows Atom objects to contain XML which is not part 
  36.       of the Atom specification, these are called extension elements. If a 
  37.       classes parser encounters an unexpected XML construct, it is translated
  38.       into an ExtensionElement instance. ExtensionElement is designed to fully
  39.       capture the information in the XML. Child nodes in an XML extension are
  40.       turned into ExtensionElements as well.
  41. """
  42.  
  43.  
  44. __author__ = 'api.jscudder (Jeffrey Scudder)'
  45.  
  46. try:
  47.   from xml.etree import cElementTree as ElementTree
  48. except ImportError:
  49.   try:
  50.     import cElementTree as ElementTree
  51.   except ImportError:
  52.     try:
  53.       from xml.etree import ElementTree
  54.     except ImportError:
  55.       from elementtree import ElementTree
  56.  
  57.  
  58. # XML namespaces which are often used in Atom entities.
  59. ATOM_NAMESPACE = 'http://www.w3.org/2005/Atom'
  60. ELEMENT_TEMPLATE = '{http://www.w3.org/2005/Atom}%s'
  61. APP_NAMESPACE = 'http://purl.org/atom/app#'
  62. APP_TEMPLATE = '{http://purl.org/atom/app#}%s'
  63.  
  64. # This encoding is used for converting strings before translating the XML
  65. # into an object.
  66. XML_STRING_ENCODING = 'utf-8'
  67. # The desired string encoding for object members. set or monkey-patch to 
  68. # unicode if you want object members to be Python unicode strings, instead of
  69. # encoded strings
  70. MEMBER_STRING_ENCODING = 'utf-8'
  71. #MEMBER_STRING_ENCODING = unicode
  72.  
  73. def CreateClassFromXMLString(target_class, xml_string, string_encoding=None):
  74.   """Creates an instance of the target class from the string contents.
  75.   
  76.   Args:
  77.     target_class: class The class which will be instantiated and populated
  78.         with the contents of the XML. This class must have a _tag and a
  79.         _namespace class variable.
  80.     xml_string: str A string which contains valid XML. The root element
  81.         of the XML string should match the tag and namespace of the desired
  82.         class.
  83.     string_encoding: str The character encoding which the xml_string should
  84.         be converted to before it is interpreted and translated into 
  85.         objects. The default is None in which case the string encoding
  86.         is not changed.
  87.  
  88.   Returns:
  89.     An instance of the target class with members assigned according to the
  90.     contents of the XML - or None if the root XML tag and namespace did not
  91.     match those of the target class.
  92.   """
  93.   encoding = string_encoding or XML_STRING_ENCODING
  94.   if encoding and isinstance(xml_string, unicode):
  95.     xml_string = xml_string.encode(encoding)
  96.   tree = ElementTree.fromstring(xml_string)
  97.   return _CreateClassFromElementTree(target_class, tree)
  98.  
  99.  
  100. def _CreateClassFromElementTree(target_class, tree, namespace=None, tag=None):
  101.   """Instantiates the class and populates members according to the tree.
  102.  
  103.   Note: Only use this function with classes that have _namespace and _tag
  104.   class members.
  105.  
  106.   Args:
  107.     target_class: class The class which will be instantiated and populated
  108.         with the contents of the XML.
  109.     tree: ElementTree An element tree whose contents will be converted into
  110.         members of the new target_class instance.
  111.     namespace: str (optional) The namespace which the XML tree's root node must
  112.         match. If omitted, the namespace defaults to the _namespace of the 
  113.         target class.
  114.     tag: str (optional) The tag which the XML tree's root node must match. If
  115.         omitted, the tag defaults to the _tag class member of the target 
  116.         class.
  117.  
  118.     Returns:
  119.       An instance of the target class - or None if the tag and namespace of 
  120.       the XML tree's root node did not match the desired namespace and tag.
  121.   """
  122.   if namespace is None:
  123.     namespace = target_class._namespace
  124.   if tag is None:
  125.     tag = target_class._tag
  126.   if tree.tag == '{%s}%s' % (namespace, tag):
  127.     target = target_class()
  128.     target._HarvestElementTree(tree)
  129.     return target
  130.   else:
  131.     return None
  132.  
  133.  
  134. class ExtensionContainer(object):
  135.   
  136.   def __init__(self, extension_elements=None, extension_attributes=None,
  137.       text=None):
  138.     self.extension_elements = extension_elements or []
  139.     self.extension_attributes = extension_attributes or {}
  140.     self.text = text
  141.  
  142.   # Three methods to create an object from an ElementTree
  143.   def _HarvestElementTree(self, tree):
  144.     # Fill in the instance members from the contents of the XML tree.
  145.     for child in tree:
  146.       self._ConvertElementTreeToMember(child)
  147.     for attribute, value in tree.attrib.iteritems():
  148.       self._ConvertElementAttributeToMember(attribute, value)
  149.     # Encode the text string according to the desired encoding type. (UTF-8)
  150.     if tree.text:
  151.       if MEMBER_STRING_ENCODING is unicode:
  152.         self.text = tree.text
  153.       else:
  154.         self.text = tree.text.encode(MEMBER_STRING_ENCODING)
  155.     
  156.   def _ConvertElementTreeToMember(self, child_tree, current_class=None):
  157.     self.extension_elements.append(_ExtensionElementFromElementTree(
  158.         child_tree))
  159.  
  160.   def _ConvertElementAttributeToMember(self, attribute, value):
  161.     # Encode the attribute value's string with the desired type Default UTF-8
  162.     if value:
  163.       if MEMBER_STRING_ENCODING is unicode:
  164.         self.extension_attributes[attribute] = value
  165.       else:
  166.         self.extension_attributes[attribute] = value.encode(
  167.           MEMBER_STRING_ENCODING)
  168.  
  169.   # One method to create an ElementTree from an object
  170.   def _AddMembersToElementTree(self, tree):
  171.     for child in self.extension_elements:
  172.       child._BecomeChildElement(tree)
  173.     for attribute, value in self.extension_attributes.iteritems():
  174.       if value:
  175.         if isinstance(value, unicode) or MEMBER_STRING_ENCODING is unicode:
  176.           tree.attrib[attribute] = value
  177.         else:
  178.           # Decode the value from the desired encoding (default UTF-8).
  179.           tree.attrib[attribute] = value.decode(MEMBER_STRING_ENCODING)
  180.     if self.text:
  181.       if isinstance(self.text, unicode) or MEMBER_STRING_ENCODING is unicode:
  182.         tree.text = self.text 
  183.       else:
  184.         tree.text = self.text.decode(MEMBER_STRING_ENCODING)
  185.  
  186.   def FindExtensions(self, tag=None, namespace=None):
  187.     """Searches extension elements for child nodes with the desired name.
  188.  
  189.     Returns a list of extension elements within this object whose tag
  190.     and/or namespace match those passed in. To find all extensions in
  191.     a particular namespace, specify the namespace but not the tag name.
  192.     If you specify only the tag, the result list may contain extension
  193.     elements in multiple namespaces.
  194.  
  195.     Args:
  196.       tag: str (optional) The desired tag
  197.       namespace: str (optional) The desired namespace
  198.  
  199.     Returns:
  200.       A list of elements whose tag and/or namespace match the parameters
  201.       values
  202.     """
  203.  
  204.     results = []
  205.  
  206.     if tag and namespace:
  207.       for element in self.extension_elements:
  208.         if element.tag == tag and element.namespace == namespace:
  209.           results.append(element)
  210.     elif tag and not namespace:
  211.       for element in self.extension_elements:
  212.         if element.tag == tag:
  213.           results.append(element)
  214.     elif namespace and not tag:
  215.       for element in self.extension_elements:
  216.         if element.namespace == namespace:
  217.           results.append(element)
  218.     else:
  219.       for element in self.extension_elements:
  220.         results.append(element)
  221.  
  222.     return results
  223.   
  224.  
  225. class AtomBase(ExtensionContainer):
  226.  
  227.   _children = {}
  228.   _attributes = {}
  229.  
  230.   def __init__(self, extension_elements=None, extension_attributes=None,
  231.       text=None):
  232.     self.extension_elements = extension_elements or []
  233.     self.extension_attributes = extension_attributes or {}
  234.     self.text = text
  235.       
  236.   def _ConvertElementTreeToMember(self, child_tree):
  237.     # Find the element's tag in this class's list of child members
  238.     if self.__class__._children.has_key(child_tree.tag):
  239.       member_name = self.__class__._children[child_tree.tag][0]
  240.       member_class = self.__class__._children[child_tree.tag][1]
  241.       # If the class member is supposed to contain a list, make sure the
  242.       # matching member is set to a list, then append the new member
  243.       # instance to the list.
  244.       if isinstance(member_class, list):
  245.         if getattr(self, member_name) is None:
  246.           setattr(self, member_name, [])
  247.         getattr(self, member_name).append(_CreateClassFromElementTree(
  248.             member_class[0], child_tree))
  249.       else:
  250.         setattr(self, member_name, 
  251.                 _CreateClassFromElementTree(member_class, child_tree))
  252.     else:
  253.       ExtensionContainer._ConvertElementTreeToMember(self, child_tree)      
  254.  
  255.   def _ConvertElementAttributeToMember(self, attribute, value):
  256.     # Find the attribute in this class's list of attributes. 
  257.     if self.__class__._attributes.has_key(attribute):
  258.       # Find the member of this class which corresponds to the XML attribute
  259.       # (lookup in current_class._attributes) and set this member to the
  260.       # desired value (using self.__dict__).
  261.       if value:
  262.         # Encode the string to capture non-ascii characters (default UTF-8)
  263.         if MEMBER_STRING_ENCODING is unicode:
  264.           setattr(self, self.__class__._attributes[attribute], value)
  265.         else:
  266.           setattr(self, self.__class__._attributes[attribute], 
  267.                 value.encode(MEMBER_STRING_ENCODING))
  268.     else:
  269.       ExtensionContainer._ConvertElementAttributeToMember(self, attribute, 
  270.           value)
  271.  
  272.   # Three methods to create an ElementTree from an object
  273.   def _AddMembersToElementTree(self, tree):
  274.     # Convert the members of this class which are XML child nodes. 
  275.     # This uses the class's _children dictionary to find the members which
  276.     # should become XML child nodes.
  277.     member_node_names = [values[0] for tag, values in 
  278.                                        self.__class__._children.iteritems()]
  279.     for member_name in member_node_names:
  280.       member = getattr(self, member_name)
  281.       if member is None:
  282.         pass
  283.       elif isinstance(member, list):
  284.         for instance in member:
  285.           instance._BecomeChildElement(tree)
  286.       else:
  287.         member._BecomeChildElement(tree)
  288.     # Convert the members of this class which are XML attributes.
  289.     for xml_attribute, member_name in self.__class__._attributes.iteritems():
  290.       member = getattr(self, member_name)
  291.       if member is not None:
  292.         if isinstance(member, unicode) or MEMBER_STRING_ENCODING is unicode:
  293.           tree.attrib[xml_attribute] = member
  294.         else:
  295.           tree.attrib[xml_attribute] = member.decode(MEMBER_STRING_ENCODING)
  296.     # Lastly, call the ExtensionContainers's _AddMembersToElementTree to 
  297.     # convert any extension attributes.
  298.     ExtensionContainer._AddMembersToElementTree(self, tree)
  299.     
  300.   
  301.   def _BecomeChildElement(self, tree):
  302.     """
  303.  
  304.     Note: Only for use with classes that have a _tag and _namespace class 
  305.     member. It is in AtomBase so that it can be inherited but it should
  306.     not be called on instances of AtomBase.
  307.     
  308.     """
  309.     new_child = ElementTree.Element('')
  310.     tree.append(new_child)
  311.     new_child.tag = '{%s}%s' % (self.__class__._namespace, 
  312.                                 self.__class__._tag)
  313.     self._AddMembersToElementTree(new_child)
  314.  
  315.   def _ToElementTree(self):
  316.     """
  317.  
  318.     Note, this method is designed to be used only with classes that have a 
  319.     _tag and _namespace. It is placed in AtomBase for inheritance but should
  320.     not be called on this class.
  321.  
  322.     """
  323.     new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
  324.                                                self.__class__._tag))
  325.     self._AddMembersToElementTree(new_tree)
  326.     return new_tree
  327.  
  328.   def ToString(self, string_encoding='UTF-8'):
  329.     """Converts the Atom object to a string containing XML."""
  330.     return ElementTree.tostring(self._ToElementTree(), encoding=string_encoding)
  331.  
  332.   def __str__(self):
  333.     return self.ToString()
  334.  
  335.     
  336. class Name(AtomBase):
  337.   """The atom:name element"""
  338.  
  339.   _tag = 'name'
  340.   _namespace = ATOM_NAMESPACE
  341.   _children = AtomBase._children.copy()
  342.   _attributes = AtomBase._attributes.copy()
  343.  
  344.   def __init__(self, text=None, extension_elements=None,
  345.       extension_attributes=None):
  346.     """Constructor for Name
  347.  
  348.     Args:
  349.       text: str The text data in the this element
  350.       extension_elements: list A  list of ExtensionElement instances
  351.       extension_attributes: dict A dictionary of attribute value string pairs
  352.     """
  353.  
  354.     self.text = text
  355.     self.extension_elements = extension_elements or []
  356.     self.extension_attributes = extension_attributes or {}
  357.  
  358.  
  359. def NameFromString(xml_string):
  360.   return CreateClassFromXMLString(Name, xml_string)
  361.  
  362.  
  363. class Email(AtomBase):
  364.   """The atom:email element"""
  365.  
  366.   _tag = 'email'
  367.   _namespace = ATOM_NAMESPACE
  368.   _children = AtomBase._children.copy()
  369.   _attributes = AtomBase._attributes.copy()
  370.   
  371.   def __init__(self, text=None, extension_elements=None,
  372.       extension_attributes=None):
  373.     """Constructor for Email
  374.  
  375.     Args:
  376.       extension_elements: list A  list of ExtensionElement instances
  377.       extension_attributes: dict A dictionary of attribute value string pairs
  378.       text: str The text data in the this element
  379.     """
  380.  
  381.     self.text = text
  382.     self.extension_elements = extension_elements or []
  383.     self.extension_attributes = extension_attributes or {}
  384.  
  385.  
  386. def EmailFromString(xml_string):
  387.   return CreateClassFromXMLString(Email, xml_string)
  388.  
  389.  
  390. class Uri(AtomBase):
  391.   """The atom:uri element"""
  392.  
  393.   _tag = 'uri'
  394.   _namespace = ATOM_NAMESPACE
  395.   _children = AtomBase._children.copy()
  396.   _attributes = AtomBase._attributes.copy()
  397.  
  398.   def __init__(self, text=None, extension_elements=None,
  399.       extension_attributes=None):
  400.     """Constructor for Uri
  401.  
  402.     Args:
  403.       extension_elements: list A  list of ExtensionElement instances
  404.       extension_attributes: dict A dictionary of attribute value string pairs
  405.       text: str The text data in the this element
  406.     """
  407.  
  408.     self.text = text
  409.     self.extension_elements = extension_elements or []
  410.     self.extension_attributes = extension_attributes or {}
  411.  
  412.  
  413. def UriFromString(xml_string):
  414.   return CreateClassFromXMLString(Uri, xml_string)
  415.  
  416.   
  417. class Person(AtomBase):
  418.   """A foundation class from which atom:author and atom:contributor extend.
  419.   
  420.   A person contains information like name, email address, and web page URI for
  421.   an author or contributor to an Atom feed. 
  422.   """
  423.  
  424.   _children = AtomBase._children.copy()
  425.   _attributes = AtomBase._attributes.copy()
  426.   _children['{%s}name' % (ATOM_NAMESPACE)] = ('name', Name)
  427.   _children['{%s}email' % (ATOM_NAMESPACE)] = ('email', Email)
  428.   _children['{%s}uri' % (ATOM_NAMESPACE)] = ('uri', Uri)
  429.  
  430.   def __init__(self, name=None, email=None, uri=None,
  431.       extension_elements=None, extension_attributes=None, text=None):
  432.     """Foundation from which author and contributor are derived.
  433.  
  434.     The constructor is provided for illustrative purposes, you should not
  435.     need to instantiate a Person.
  436.  
  437.     Args:
  438.       name: Name The person's name
  439.       email: Email The person's email address
  440.       uri: Uri The URI of the person's webpage
  441.       extension_elements: list A list of ExtensionElement instances which are
  442.           children of this element.
  443.       extension_attributes: dict A dictionary of strings which are the values
  444.           for additional XML attributes of this element.
  445.       text: String The text contents of the element. This is the contents
  446.           of the Entry's XML text node. (Example: <foo>This is the text</foo>)
  447.     """
  448.  
  449.     self.name = name
  450.     self.email = email
  451.     self.uri = uri
  452.     self.extension_elements = extension_elements or []
  453.     self.extension_attributes = extension_attributes or {}
  454.     self.text = text
  455.  
  456.  
  457. class Author(Person):
  458.   """The atom:author element
  459.   
  460.   An author is a required element in Feed. 
  461.   """
  462.  
  463.   _tag = 'author'
  464.   _namespace = ATOM_NAMESPACE
  465.   _children = Person._children.copy()
  466.   _attributes = Person._attributes.copy()
  467.   #_children = {}
  468.   #_attributes = {}
  469.  
  470.   def __init__(self, name=None, email=None, uri=None, 
  471.       extension_elements=None, extension_attributes=None, text=None):
  472.     """Constructor for Author
  473.     
  474.     Args:
  475.       name: Name
  476.       email: Email
  477.       uri: Uri
  478.       extension_elements: list A  list of ExtensionElement instances
  479.       extension_attributes: dict A dictionary of attribute value string pairs
  480.       text: str The text data in the this element
  481.     """
  482.     
  483.     self.name = name
  484.     self.email = email
  485.     self.uri = uri
  486.     self.extension_elements = extension_elements or []
  487.     self.extension_attributes = extension_attributes or {}
  488.     self.text = text
  489.  
  490.     
  491. def AuthorFromString(xml_string):
  492.   return CreateClassFromXMLString(Author, xml_string)
  493.   
  494.  
  495. class Contributor(Person):
  496.   """The atom:contributor element"""
  497.  
  498.   _tag = 'contributor'
  499.   _namespace = ATOM_NAMESPACE
  500.   _children = Person._children.copy()
  501.   _attributes = Person._attributes.copy()
  502.  
  503.   def __init__(self, name=None, email=None, uri=None,
  504.       extension_elements=None, extension_attributes=None, text=None):
  505.     """Constructor for Contributor
  506.     
  507.     Args:
  508.       name: Name
  509.       email: Email
  510.       uri: Uri
  511.       extension_elements: list A  list of ExtensionElement instances
  512.       extension_attributes: dict A dictionary of attribute value string pairs
  513.       text: str The text data in the this element
  514.     """
  515.  
  516.     self.name = name
  517.     self.email = email
  518.     self.uri = uri
  519.     self.extension_elements = extension_elements or []
  520.     self.extension_attributes = extension_attributes or {}
  521.     self.text = text
  522.  
  523.  
  524. def ContributorFromString(xml_string):
  525.   return CreateClassFromXMLString(Contributor, xml_string)
  526.   
  527.   
  528. class Link(AtomBase):
  529.   """The atom:link element"""
  530.  
  531.   _tag = 'link'
  532.   _namespace = ATOM_NAMESPACE
  533.   _children = AtomBase._children.copy()
  534.   _attributes = AtomBase._attributes.copy()
  535.   _attributes['rel'] = 'rel'
  536.   _attributes['href'] = 'href'
  537.   _attributes['type'] = 'type'
  538.   _attributes['title'] = 'title'
  539.   _attributes['length'] = 'length'
  540.   _attributes['hreflang'] = 'hreflang'
  541.   
  542.   def __init__(self, href=None, rel=None, link_type=None, hreflang=None, 
  543.       title=None, length=None, text=None, extension_elements=None, 
  544.       extension_attributes=None):
  545.     """Constructor for Link
  546.     
  547.     Args:
  548.       href: string The href attribute of the link
  549.       rel: string
  550.       type: string
  551.       hreflang: string The language for the href
  552.       title: string
  553.       length: string The length of the href's destination
  554.       extension_elements: list A  list of ExtensionElement instances
  555.       extension_attributes: dict A dictionary of attribute value string pairs
  556.       text: str The text data in the this element
  557.     """
  558.  
  559.     self.href = href
  560.     self.rel = rel
  561.     self.type = link_type
  562.     self.hreflang = hreflang
  563.     self.title = title
  564.     self.length = length
  565.     self.text = text
  566.     self.extension_elements = extension_elements or []
  567.     self.extension_attributes = extension_attributes or {}
  568.  
  569.  
  570. def LinkFromString(xml_string):
  571.   return CreateClassFromXMLString(Link, xml_string)
  572.   
  573.  
  574. class Generator(AtomBase):
  575.   """The atom:generator element"""
  576.  
  577.   _tag = 'generator'
  578.   _namespace = ATOM_NAMESPACE
  579.   _children = AtomBase._children.copy()
  580.   _attributes = AtomBase._attributes.copy()
  581.   _attributes['uri'] = 'uri'
  582.   _attributes['version'] = 'version'
  583.  
  584.   def __init__(self, uri=None, version=None, text=None, 
  585.       extension_elements=None, extension_attributes=None):
  586.     """Constructor for Generator
  587.     
  588.     Args:
  589.       uri: string
  590.       version: string
  591.       text: str The text data in the this element
  592.       extension_elements: list A  list of ExtensionElement instances
  593.       extension_attributes: dict A dictionary of attribute value string pairs
  594.     """
  595.  
  596.     self.uri = uri
  597.     self.version = version
  598.     self.text = text
  599.     self.extension_elements = extension_elements or []
  600.     self.extension_attributes = extension_attributes or {}
  601.  
  602. def GeneratorFromString(xml_string):
  603.   return CreateClassFromXMLString(Generator, xml_string)
  604.  
  605.  
  606. class Text(AtomBase):
  607.   """A foundation class from which atom:title, summary, etc. extend.
  608.   
  609.   This class should never be instantiated.
  610.   """
  611.  
  612.   _children = AtomBase._children.copy()
  613.   _attributes = AtomBase._attributes.copy()
  614.   _attributes['type'] = 'type'
  615.  
  616.   def __init__(self, text_type=None, text=None, extension_elements=None,
  617.       extension_attributes=None):
  618.     """Constructor for Text
  619.     
  620.     Args:
  621.       text_type: string
  622.       text: str The text data in the this element
  623.       extension_elements: list A  list of ExtensionElement instances
  624.       extension_attributes: dict A dictionary of attribute value string pairs
  625.     """
  626.     
  627.     self.type = text_type
  628.     self.text = text
  629.     self.extension_elements = extension_elements or []
  630.     self.extension_attributes = extension_attributes or {}
  631.  
  632.  
  633. class Title(Text):
  634.   """The atom:title element"""
  635.  
  636.   _tag = 'title'
  637.   _namespace = ATOM_NAMESPACE
  638.   _children = Text._children.copy()
  639.   _attributes = Text._attributes.copy()
  640.  
  641.   def __init__(self, title_type=None, text=None, extension_elements=None,
  642.       extension_attributes=None):
  643.     """Constructor for Title
  644.     
  645.     Args:
  646.       title_type: string
  647.       text: str The text data in the this element
  648.       extension_elements: list A  list of ExtensionElement instances
  649.       extension_attributes: dict A dictionary of attribute value string pairs
  650.     """
  651.  
  652.     self.type = title_type
  653.     self.text = text
  654.     self.extension_elements = extension_elements or []
  655.     self.extension_attributes = extension_attributes or {}
  656.  
  657.  
  658. def TitleFromString(xml_string):
  659.   return CreateClassFromXMLString(Title, xml_string)
  660.  
  661.  
  662. class Subtitle(Text):
  663.   """The atom:subtitle element"""
  664.  
  665.   _tag = 'subtitle'
  666.   _namespace = ATOM_NAMESPACE
  667.   _children = Text._children.copy()
  668.   _attributes = Text._attributes.copy()
  669.  
  670.   def __init__(self, subtitle_type=None, text=None, extension_elements=None,
  671.       extension_attributes=None):
  672.     """Constructor for Subtitle
  673.     
  674.     Args:
  675.       subtitle_type: string
  676.       text: str The text data in the this element
  677.       extension_elements: list A  list of ExtensionElement instances
  678.       extension_attributes: dict A dictionary of attribute value string pairs
  679.     """
  680.  
  681.     self.type = subtitle_type
  682.     self.text = text
  683.     self.extension_elements = extension_elements or []
  684.     self.extension_attributes = extension_attributes or {}
  685.  
  686.  
  687. def SubtitleFromString(xml_string):
  688.   return CreateClassFromXMLString(Subtitle, xml_string)
  689.  
  690.  
  691. class Rights(Text):
  692.   """The atom:rights element"""
  693.  
  694.   _tag = 'rights'
  695.   _namespace = ATOM_NAMESPACE
  696.   _children = Text._children.copy()
  697.   _attributes = Text._attributes.copy()
  698.  
  699.   def __init__(self, rights_type=None, text=None, extension_elements=None,
  700.       extension_attributes=None):
  701.     """Constructor for Rights
  702.     
  703.     Args:
  704.       rights_type: string
  705.       text: str The text data in the this element
  706.       extension_elements: list A  list of ExtensionElement instances
  707.       extension_attributes: dict A dictionary of attribute value string pairs
  708.     """
  709.  
  710.     self.type = rights_type
  711.     self.text = text
  712.     self.extension_elements = extension_elements or []
  713.     self.extension_attributes = extension_attributes or {}
  714.  
  715.  
  716. def RightsFromString(xml_string):
  717.   return CreateClassFromXMLString(Rights, xml_string)
  718.  
  719.  
  720. class Summary(Text):
  721.   """The atom:summary element"""
  722.  
  723.   _tag = 'summary'
  724.   _namespace = ATOM_NAMESPACE
  725.   _children = Text._children.copy()
  726.   _attributes = Text._attributes.copy()
  727.  
  728.   def __init__(self, summary_type=None, text=None, extension_elements=None,
  729.       extension_attributes=None):
  730.     """Constructor for Summary
  731.     
  732.     Args:
  733.       summary_type: string
  734.       text: str The text data in the this element
  735.       extension_elements: list A  list of ExtensionElement instances
  736.       extension_attributes: dict A dictionary of attribute value string pairs
  737.     """
  738.  
  739.     self.type = summary_type
  740.     self.text = text
  741.     self.extension_elements = extension_elements or []
  742.     self.extension_attributes = extension_attributes or {}
  743.  
  744.  
  745. def SummaryFromString(xml_string):
  746.   return CreateClassFromXMLString(Summary, xml_string)
  747.  
  748.  
  749. class Content(Text):
  750.   """The atom:content element"""
  751.  
  752.   _tag = 'content'
  753.   _namespace = ATOM_NAMESPACE
  754.   _children = Text._children.copy()
  755.   _attributes = Text._attributes.copy()
  756.   _attributes['src'] = 'src'
  757.  
  758.   def __init__(self, content_type=None, src=None, text=None, 
  759.       extension_elements=None, extension_attributes=None):
  760.     """Constructor for Content
  761.     
  762.     Args:
  763.       content_type: string
  764.       src: string
  765.       text: str The text data in the this element
  766.       extension_elements: list A  list of ExtensionElement instances
  767.       extension_attributes: dict A dictionary of attribute value string pairs
  768.     """
  769.     
  770.     self.type = content_type
  771.     self.src = src
  772.     self.text = text
  773.     self.extension_elements = extension_elements or []
  774.     self.extension_attributes = extension_attributes or {}
  775.  
  776. def ContentFromString(xml_string):
  777.   return CreateClassFromXMLString(Content, xml_string)
  778.  
  779.  
  780. class Category(AtomBase):
  781.   """The atom:category element"""
  782.  
  783.   _tag = 'category'
  784.   _namespace = ATOM_NAMESPACE
  785.   _children = AtomBase._children.copy()
  786.   _attributes = AtomBase._attributes.copy()
  787.   _attributes['term'] = 'term'
  788.   _attributes['scheme'] = 'scheme'
  789.   _attributes['label'] = 'label'
  790.  
  791.   def __init__(self, term=None, scheme=None, label=None, text=None, 
  792.       extension_elements=None, extension_attributes=None):
  793.     """Constructor for Category
  794.     
  795.     Args:
  796.       term: str
  797.       scheme: str
  798.       label: str
  799.       text: str The text data in the this element
  800.       extension_elements: list A  list of ExtensionElement instances
  801.       extension_attributes: dict A dictionary of attribute value string pairs
  802.     """
  803.     
  804.     self.term = term
  805.     self.scheme = scheme
  806.     self.label = label
  807.     self.text = text
  808.     self.extension_elements = extension_elements or []
  809.     self.extension_attributes = extension_attributes or {}
  810.  
  811.  
  812. def CategoryFromString(xml_string):
  813.   return CreateClassFromXMLString(Category, xml_string)
  814.  
  815.  
  816. class Id(AtomBase):
  817.   """The atom:id element."""
  818.  
  819.   _tag = 'id'
  820.   _namespace = ATOM_NAMESPACE
  821.   _children = AtomBase._children.copy()
  822.   _attributes = AtomBase._attributes.copy()
  823.  
  824.   def __init__(self, text=None, extension_elements=None,
  825.       extension_attributes=None):
  826.     """Constructor for Id
  827.     
  828.     Args:
  829.       text: str The text data in the this element
  830.       extension_elements: list A  list of ExtensionElement instances
  831.       extension_attributes: dict A dictionary of attribute value string pairs
  832.     """
  833.  
  834.     self.text = text
  835.     self.extension_elements = extension_elements or []
  836.     self.extension_attributes = extension_attributes or {}
  837.  
  838.  
  839. def IdFromString(xml_string):
  840.   return CreateClassFromXMLString(Id, xml_string)
  841.  
  842.  
  843. class Icon(AtomBase):
  844.   """The atom:icon element."""
  845.   
  846.   _tag = 'icon'
  847.   _namespace = ATOM_NAMESPACE
  848.   _children = AtomBase._children.copy()
  849.   _attributes = AtomBase._attributes.copy()
  850.  
  851.   def __init__(self, text=None, extension_elements=None,
  852.       extension_attributes=None):
  853.     """Constructor for Icon
  854.     
  855.     Args:
  856.       text: str The text data in the this element
  857.       extension_elements: list A  list of ExtensionElement instances
  858.       extension_attributes: dict A dictionary of attribute value string pairs
  859.     """
  860.  
  861.     self.text = text
  862.     self.extension_elements = extension_elements or []
  863.     self.extension_attributes = extension_attributes or {}
  864.  
  865.  
  866. def IconFromString(xml_string):
  867.   return CreateClassFromXMLString(Icon, xml_string)
  868.  
  869.  
  870. class Logo(AtomBase):
  871.   """The atom:logo element."""
  872.  
  873.   _tag = 'logo'
  874.   _namespace = ATOM_NAMESPACE
  875.   _children = AtomBase._children.copy()
  876.   _attributes = AtomBase._attributes.copy()
  877.  
  878.   def __init__(self, text=None, extension_elements=None,
  879.       extension_attributes=None):
  880.     """Constructor for Logo
  881.     
  882.     Args:
  883.       text: str The text data in the this element
  884.       extension_elements: list A  list of ExtensionElement instances
  885.       extension_attributes: dict A dictionary of attribute value string pairs
  886.     """
  887.     
  888.     self.text = text
  889.     self.extension_elements = extension_elements or []
  890.     self.extension_attributes = extension_attributes or {}
  891.  
  892.  
  893. def LogoFromString(xml_string):
  894.   return CreateClassFromXMLString(Logo, xml_string)
  895.  
  896.  
  897. class Draft(AtomBase):
  898.   """The app:draft element which indicates if this entry should be public."""
  899.  
  900.   _tag = 'draft'
  901.   _namespace = APP_NAMESPACE
  902.   _children = AtomBase._children.copy()
  903.   _attributes = AtomBase._attributes.copy()
  904.  
  905.   def __init__(self, text=None, extension_elements=None,
  906.       extension_attributes=None):
  907.     """Constructor for app:draft
  908.  
  909.     Args:
  910.       text: str The text data in the this element
  911.       extension_elements: list A  list of ExtensionElement instances
  912.       extension_attributes: dict A dictionary of attribute value string pairs
  913.     """
  914.  
  915.     self.text = text
  916.     self.extension_elements = extension_elements or []
  917.     self.extension_attributes = extension_attributes or {}
  918.  
  919.  
  920. def DraftFromString(xml_string):
  921.   return CreateClassFromXMLString(Draft, xml_string)
  922.  
  923.  
  924. class Control(AtomBase):
  925.   """The app:control element indicating restrictions on publication.
  926.   
  927.   The APP control element may contain a draft element indicating whether or
  928.   not this entry should be publicly available.
  929.   """
  930.  
  931.   _tag = 'control'
  932.   _namespace = APP_NAMESPACE
  933.   _children = AtomBase._children.copy()
  934.   _attributes = AtomBase._attributes.copy()
  935.   _children['{%s}draft' % APP_NAMESPACE] = ('draft', Draft)
  936.  
  937.   def __init__(self, draft=None, text=None, extension_elements=None,
  938.         extension_attributes=None):
  939.     """Constructor for app:control"""
  940.     
  941.     self.draft = draft
  942.     self.text = text
  943.     self.extension_elements = extension_elements or []
  944.     self.extension_attributes = extension_attributes or {}
  945.  
  946.  
  947. def ControlFromString(xml_string):
  948.   return CreateClassFromXMLString(Control, xml_string)
  949.  
  950.  
  951. class Date(AtomBase):
  952.   """A parent class for atom:updated, published, etc."""
  953.  
  954.   #TODO Add text to and from time conversion methods to allow users to set
  955.   # the contents of a Date to a python DateTime object.
  956.  
  957.   _children = AtomBase._children.copy()
  958.   _attributes = AtomBase._attributes.copy()
  959.  
  960.   def __init__(self, text=None, extension_elements=None,
  961.       extension_attributes=None):
  962.     self.text = text
  963.     self.extension_elements = extension_elements or []
  964.     self.extension_attributes = extension_attributes or {}
  965.  
  966.  
  967. class Updated(Date):
  968.   """The atom:updated element."""
  969.  
  970.   _tag = 'updated'
  971.   _namespace = ATOM_NAMESPACE
  972.   _children = Date._children.copy()
  973.   _attributes = Date._attributes.copy()
  974.  
  975.   def __init__(self, text=None, extension_elements=None,
  976.       extension_attributes=None):
  977.     """Constructor for Updated
  978.     
  979.     Args:
  980.       text: str The text data in the this element
  981.       extension_elements: list A  list of ExtensionElement instances
  982.       extension_attributes: dict A dictionary of attribute value string pairs
  983.     """
  984.  
  985.     self.text = text
  986.     self.extension_elements = extension_elements or []
  987.     self.extension_attributes = extension_attributes or {}
  988.  
  989.  
  990. def UpdatedFromString(xml_string):
  991.   return CreateClassFromXMLString(Updated, xml_string)
  992.  
  993.  
  994. class Published(Date):
  995.   """The atom:published element."""
  996.  
  997.   _tag = 'published'
  998.   _namespace = ATOM_NAMESPACE
  999.   _children = Date._children.copy()
  1000.   _attributes = Date._attributes.copy()
  1001.  
  1002.   def __init__(self, text=None, extension_elements=None,
  1003.       extension_attributes=None):
  1004.     """Constructor for Published
  1005.     
  1006.     Args:
  1007.       text: str The text data in the this element
  1008.       extension_elements: list A  list of ExtensionElement instances
  1009.       extension_attributes: dict A dictionary of attribute value string pairs
  1010.     """
  1011.  
  1012.     self.text = text
  1013.     self.extension_elements = extension_elements or []
  1014.     self.extension_attributes = extension_attributes or {}
  1015.  
  1016.  
  1017. def PublishedFromString(xml_string):
  1018.   return CreateClassFromXMLString(Published, xml_string)
  1019.  
  1020.  
  1021. class LinkFinder(object):
  1022.   """An "interface" providing methods to find link elements
  1023.  
  1024.   Entry elements often contain multiple links which differ in the rel
  1025.   attribute or content type. Often, developers are interested in a specific
  1026.   type of link so this class provides methods to find specific classes of
  1027.   links.
  1028.  
  1029.   This class is used as a mixin in Atom entries and feeds.
  1030.   """
  1031.  
  1032.   def GetSelfLink(self):
  1033.     """Find the first link with rel set to 'self'
  1034.  
  1035.     Returns:
  1036.       An atom.Link or none if none of the links had rel equal to 'self'
  1037.     """
  1038.  
  1039.     for a_link in self.link:
  1040.       if a_link.rel == 'self':
  1041.         return a_link
  1042.     return None
  1043.  
  1044.   def GetEditLink(self):
  1045.     for a_link in self.link:
  1046.       if a_link.rel == 'edit':
  1047.         return a_link
  1048.     return None
  1049.  
  1050.   def GetNextLink(self):
  1051.     for a_link in self.link:
  1052.       if a_link.rel == 'next':
  1053.         return a_link
  1054.     return None
  1055.  
  1056.   def GetLicenseLink(self):
  1057.     for a_link in self.link:
  1058.       if a_link.rel == 'license':
  1059.         return a_link
  1060.     return None
  1061.  
  1062.   def GetAlternateLink(self):
  1063.     for a_link in self.link:
  1064.       if a_link.rel == 'alternate':
  1065.         return a_link
  1066.     return None
  1067.     
  1068.  
  1069. class FeedEntryParent(AtomBase, LinkFinder):
  1070.   """A super class for atom:feed and entry, contains shared attributes"""
  1071.  
  1072.   _children = AtomBase._children.copy()
  1073.   _attributes = AtomBase._attributes.copy()
  1074.   _children['{%s}author' % ATOM_NAMESPACE] = ('author', [Author])
  1075.   _children['{%s}category' % ATOM_NAMESPACE] = ('category', [Category])
  1076.   _children['{%s}contributor' % ATOM_NAMESPACE] = ('contributor', [Contributor])
  1077.   _children['{%s}id' % ATOM_NAMESPACE] = ('id', Id)
  1078.   _children['{%s}link' % ATOM_NAMESPACE] = ('link', [Link])
  1079.   _children['{%s}rights' % ATOM_NAMESPACE] = ('rights', Rights)
  1080.   _children['{%s}title' % ATOM_NAMESPACE] = ('title', Title)
  1081.   _children['{%s}updated' % ATOM_NAMESPACE] = ('updated', Updated)
  1082.  
  1083.   def __init__(self, author=None, category=None, contributor=None, 
  1084.       atom_id=None, link=None, rights=None, title=None, updated=None, 
  1085.       text=None, extension_elements=None, extension_attributes=None):
  1086.     self.author = author or []
  1087.     self.category = category or []
  1088.     self.contributor = contributor or []
  1089.     self.id = atom_id
  1090.     self.link = link or []
  1091.     self.rights = rights
  1092.     self.title = title
  1093.     self.updated = updated
  1094.     self.text = text
  1095.     self.extension_elements = extension_elements or []
  1096.     self.extension_attributes = extension_attributes or {}
  1097.  
  1098.  
  1099. class Source(FeedEntryParent):
  1100.   """The atom:source element"""
  1101.  
  1102.   _tag = 'source'
  1103.   _namespace = ATOM_NAMESPACE
  1104.   _children = FeedEntryParent._children.copy()
  1105.   _attributes = FeedEntryParent._attributes.copy()
  1106.   _children['{%s}generator' % ATOM_NAMESPACE] = ('generator', Generator)
  1107.   _children['{%s}icon' % ATOM_NAMESPACE] = ('icon', Icon)
  1108.   _children['{%s}logo' % ATOM_NAMESPACE] = ('logo', Logo)
  1109.   _children['{%s}subtitle' % ATOM_NAMESPACE] = ('subtitle', Subtitle)
  1110.  
  1111.   def __init__(self, author=None, category=None, contributor=None,
  1112.       generator=None, icon=None, atom_id=None, link=None, logo=None, 
  1113.       rights=None, subtitle=None, title=None, updated=None, text=None,
  1114.       extension_elements=None, extension_attributes=None):
  1115.     """Constructor for Source
  1116.  
  1117.     Args:
  1118.       author: list (optional) A list of Author instances which belong to this
  1119.           class.
  1120.       category: list (optional) A list of Category instances
  1121.       contributor: list (optional) A list on Contributor instances
  1122.       generator: Generator (optional)
  1123.       icon: Icon (optional)
  1124.       id: Id (optional) The entry's Id element
  1125.       link: list (optional) A list of Link instances
  1126.       logo: Logo (optional)
  1127.       rights: Rights (optional) The entry's Rights element
  1128.       subtitle: Subtitle (optional) The entry's subtitle element
  1129.       title: Title (optional) the entry's title element
  1130.       updated: Updated (optional) the entry's updated element
  1131.       text: String (optional) The text contents of the element. This is the
  1132.           contents of the Entry's XML text node.
  1133.           (Example: <foo>This is the text</foo>)
  1134.       extension_elements: list (optional) A list of ExtensionElement instances
  1135.           which are children of this element.
  1136.       extension_attributes: dict (optional) A dictionary of strings which are
  1137.           the values for additional XML attributes of this element.
  1138.     """
  1139.  
  1140.     self.author = author or []
  1141.     self.category = category or []
  1142.     self.contributor = contributor or []
  1143.     self.generator = generator
  1144.     self.icon = icon
  1145.     self.id = atom_id
  1146.     self.link = link or []
  1147.     self.logo = logo
  1148.     self.rights = rights
  1149.     self.subtitle = subtitle
  1150.     self.title = title
  1151.     self.updated = updated
  1152.     self.text = text
  1153.     self.extension_elements = extension_elements or []
  1154.     self.extension_attributes = extension_attributes or {}
  1155.  
  1156.  
  1157. def SourceFromString(xml_string):
  1158.   return CreateClassFromXMLString(Source, xml_string)
  1159.  
  1160.  
  1161. class Entry(FeedEntryParent):
  1162.   """The atom:entry element"""
  1163.  
  1164.   _tag = 'entry'
  1165.   _namespace = ATOM_NAMESPACE
  1166.   _children = FeedEntryParent._children.copy()
  1167.   _attributes = FeedEntryParent._attributes.copy()
  1168.   _children['{%s}content' % ATOM_NAMESPACE] = ('content', Content)
  1169.   _children['{%s}published' % ATOM_NAMESPACE] = ('published', Published)
  1170.   _children['{%s}source' % ATOM_NAMESPACE] = ('source', Source)
  1171.   _children['{%s}summary' % ATOM_NAMESPACE] = ('summary', Summary)
  1172.   _children['{%s}control' % APP_NAMESPACE] = ('control', Control)
  1173.  
  1174.   def __init__(self, author=None, category=None, content=None, 
  1175.       contributor=None, atom_id=None, link=None, published=None, rights=None,
  1176.       source=None, summary=None, control=None, title=None, updated=None,
  1177.       extension_elements=None, extension_attributes=None, text=None):
  1178.     """Constructor for atom:entry
  1179.  
  1180.     Args:
  1181.       author: list A list of Author instances which belong to this class.
  1182.       category: list A list of Category instances
  1183.       content: Content The entry's Content
  1184.       contributor: list A list on Contributor instances
  1185.       id: Id The entry's Id element
  1186.       link: list A list of Link instances
  1187.       published: Published The entry's Published element
  1188.       rights: Rights The entry's Rights element
  1189.       source: Source the entry's source element
  1190.       summary: Summary the entry's summary element
  1191.       title: Title the entry's title element
  1192.       updated: Updated the entry's updated element
  1193.       control: The entry's app:control element which can be used to mark an 
  1194.           entry as a draft which should not be publicly viewable.
  1195.       text: String The text contents of the element. This is the contents
  1196.           of the Entry's XML text node. (Example: <foo>This is the text</foo>)
  1197.       extension_elements: list A list of ExtensionElement instances which are
  1198.           children of this element.
  1199.       extension_attributes: dict A dictionary of strings which are the values
  1200.           for additional XML attributes of this element.
  1201.     """
  1202.  
  1203.     self.author = author or []
  1204.     self.category = category or []
  1205.     self.content = content
  1206.     self.contributor = contributor or []
  1207.     self.id = atom_id
  1208.     self.link = link or []
  1209.     self.published = published
  1210.     self.rights = rights
  1211.     self.source = source
  1212.     self.summary = summary
  1213.     self.title = title
  1214.     self.updated = updated
  1215.     self.control = control
  1216.     self.text = text
  1217.     self.extension_elements = extension_elements or []
  1218.     self.extension_attributes = extension_attributes or {}
  1219.  
  1220.  
  1221. def EntryFromString(xml_string):
  1222.   return CreateClassFromXMLString(Entry, xml_string)
  1223.  
  1224.  
  1225. class Feed(Source):
  1226.   """The atom:feed element"""
  1227.  
  1228.   _tag = 'feed'
  1229.   _namespace = ATOM_NAMESPACE
  1230.   _children = Source._children.copy()
  1231.   _attributes = Source._attributes.copy()
  1232.   _children['{%s}entry' % ATOM_NAMESPACE] = ('entry', [Entry])
  1233.  
  1234.   def __init__(self, author=None, category=None, contributor=None,
  1235.       generator=None, icon=None, atom_id=None, link=None, logo=None, 
  1236.       rights=None, subtitle=None, title=None, updated=None, entry=None, 
  1237.       text=None, extension_elements=None, extension_attributes=None):
  1238.     """Constructor for Source
  1239.     
  1240.     Args:
  1241.       author: list (optional) A list of Author instances which belong to this
  1242.           class.
  1243.       category: list (optional) A list of Category instances
  1244.       contributor: list (optional) A list on Contributor instances
  1245.       generator: Generator (optional) 
  1246.       icon: Icon (optional) 
  1247.       id: Id (optional) The entry's Id element
  1248.       link: list (optional) A list of Link instances
  1249.       logo: Logo (optional) 
  1250.       rights: Rights (optional) The entry's Rights element
  1251.       subtitle: Subtitle (optional) The entry's subtitle element
  1252.       title: Title (optional) the entry's title element
  1253.       updated: Updated (optional) the entry's updated element
  1254.       entry: list (optional) A list of the Entry instances contained in the 
  1255.           feed.
  1256.       text: String (optional) The text contents of the element. This is the 
  1257.           contents of the Entry's XML text node. 
  1258.           (Example: <foo>This is the text</foo>)
  1259.       extension_elements: list (optional) A list of ExtensionElement instances
  1260.           which are children of this element.
  1261.       extension_attributes: dict (optional) A dictionary of strings which are 
  1262.           the values for additional XML attributes of this element.
  1263.     """
  1264.  
  1265.     self.author = author or []
  1266.     self.category = category or []
  1267.     self.contributor = contributor or []
  1268.     self.generator = generator
  1269.     self.icon = icon
  1270.     self.id = atom_id
  1271.     self.link = link or []
  1272.     self.logo = logo
  1273.     self.rights = rights
  1274.     self.subtitle = subtitle
  1275.     self.title = title
  1276.     self.updated = updated
  1277.     self.entry = entry or []
  1278.     self.text = text
  1279.     self.extension_elements = extension_elements or []
  1280.     self.extension_attributes = extension_attributes or {}
  1281.  
  1282.  
  1283. def FeedFromString(xml_string):
  1284.   return CreateClassFromXMLString(Feed, xml_string)
  1285.   
  1286.   
  1287. class ExtensionElement(object):
  1288.   """Represents extra XML elements contained in Atom classes."""
  1289.   
  1290.   def __init__(self, tag, namespace=None, attributes=None, 
  1291.       children=None, text=None):
  1292.     """Constructor for EtensionElement
  1293.  
  1294.     Args:
  1295.       namespace: string (optional) The XML namespace for this element.
  1296.       tag: string (optional) The tag (without the namespace qualifier) for
  1297.           this element. To reconstruct the full qualified name of the element,
  1298.           combine this tag with the namespace.
  1299.       attributes: dict (optinal) The attribute value string pairs for the XML 
  1300.           attributes of this element.
  1301.       children: list (optional) A list of ExtensionElements which represent 
  1302.           the XML child nodes of this element.
  1303.     """
  1304.  
  1305.     self.namespace = namespace
  1306.     self.tag = tag
  1307.     self.attributes = attributes or {}
  1308.     self.children = children or []
  1309.     self.text = text
  1310.     
  1311.   def ToString(self):
  1312.     element_tree = self._TransferToElementTree(ElementTree.Element(''))
  1313.     return ElementTree.tostring(element_tree, encoding="UTF-8")
  1314.     
  1315.   def _TransferToElementTree(self, element_tree):
  1316.     if self.tag is None:
  1317.       return None
  1318.       
  1319.     if self.namespace is not None:
  1320.       element_tree.tag = '{%s}%s' % (self.namespace, self.tag)
  1321.     else:
  1322.       element_tree.tag = self.tag
  1323.       
  1324.     for key, value in self.attributes.iteritems():
  1325.       element_tree.attrib[key] = value
  1326.       
  1327.     for child in self.children:
  1328.       child._BecomeChildElement(element_tree)
  1329.       
  1330.     element_tree.text = self.text
  1331.       
  1332.     return element_tree
  1333.  
  1334.   def _BecomeChildElement(self, element_tree):
  1335.     """Converts this object into an etree element and adds it as a child node.
  1336.  
  1337.     Adds self to the ElementTree. This method is required to avoid verbose XML
  1338.     which constantly redefines the namespace.
  1339.  
  1340.     Args:
  1341.       element_tree: ElementTree._Element The element to which this object's XML
  1342.           will be added.
  1343.     """
  1344.     new_element = ElementTree.Element('')
  1345.     element_tree.append(new_element)
  1346.     self._TransferToElementTree(new_element)
  1347.  
  1348.   def FindChildren(self, tag=None, namespace=None):
  1349.     """Searches child nodes for objects with the desired tag/namespace.
  1350.  
  1351.     Returns a list of extension elements within this object whose tag
  1352.     and/or namespace match those passed in. To find all children in
  1353.     a particular namespace, specify the namespace but not the tag name.
  1354.     If you specify only the tag, the result list may contain extension
  1355.     elements in multiple namespaces.
  1356.  
  1357.     Args:
  1358.       tag: str (optional) The desired tag
  1359.       namespace: str (optional) The desired namespace
  1360.  
  1361.     Returns:
  1362.       A list of elements whose tag and/or namespace match the parameters
  1363.       values
  1364.     """
  1365.  
  1366.     results = []
  1367.  
  1368.     if tag and namespace:
  1369.       for element in self.children:
  1370.         if element.tag == tag and element.namespace == namespace:
  1371.           results.append(element)
  1372.     elif tag and not namespace:
  1373.       for element in self.children:
  1374.         if element.tag == tag:
  1375.           results.append(element)
  1376.     elif namespace and not tag:
  1377.       for element in self.children:
  1378.         if element.namespace == namespace:
  1379.           results.append(element)
  1380.     else:
  1381.       for element in self.children:
  1382.         results.append(element)
  1383.  
  1384.     return results
  1385.  
  1386.     
  1387. def ExtensionElementFromString(xml_string):
  1388.   element_tree = ElementTree.fromstring(xml_string)
  1389.   return _ExtensionElementFromElementTree(element_tree)
  1390.  
  1391.  
  1392. def _ExtensionElementFromElementTree(element_tree):
  1393.   element_tag = element_tree.tag
  1394.   if '}' in element_tag:
  1395.     namespace = element_tag[1:element_tag.index('}')]
  1396.     tag = element_tag[element_tag.index('}')+1:]
  1397.   else: 
  1398.     namespace = None
  1399.     tag = element_tag
  1400.   extension = ExtensionElement(namespace=namespace, tag=tag)
  1401.   for key, value in element_tree.attrib.iteritems():
  1402.     extension.attributes[key] = value
  1403.   for child in element_tree:
  1404.     extension.children.append(_ExtensionElementFromElementTree(child))
  1405.   extension.text = element_tree.text
  1406.   return extension
  1407.